var global = {api_url: 'http://localhost:8900',local_img_url:'http://localhost:8900/coc_api'};
window.onload=function(){//做初始化,同时做页面统计
    layui.use(['jquery'],function () {
        var $= layui.jquery;
   var path=getRealPath().toString();
   let number1 = path.indexOf("?");
   let number = path.indexOf("pages")+5;
    var respath="";
   if (number1== -1){
       respath=  ".."+path.substr(number)
   }else {
       respath=".."+path.substring(number,number1);
   }
   //判断页面路径,如果是后台页面,应存入相关用户的访问数据,如果是登录页,不记录访问情况,是网站页面,存入访问数量
        if (respath.indexOf("login")== -1) {
            var pageType=0;
            var headers={content_type: "application/json;charset=UTF-8"};
            if (respath.indexOf("web")!=-1){//不是网址页面
                headers={content_type: "application/json;charset=UTF-8",Authorization:getUser().token};
                pageType=1;
            }
            new APIRequest(
                {
                    url: global.api_url + "/unLogin/scanPageCount/countPage",
                    header: headers,
                    method: "Post",
                    async: false,
                    data: {respath:respath,pageType:pageType},
                    success: function (result) {

                    },
                    dataType: "json"
                }
            );
        }

    });
}
/**
 * 获取url中的参数
 * @param name
 * @returns {null}
 */
var GetUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}
/**
 * 获取表单json数据
 * @param fromname
 * @returns {{}}
 * @constructor
 */
/**
 *
 * @param fromname 表单id名称
 * @constructor 返回该表单中值不为空的json串
 */
var GetForm = function (fromname) {
        var  $ = layui.jquery;
        var Json = {};
        var te=$("#"+fromname).serializeArray();
        $.each(te, function () {
            if (this.value != "") {
                Json[this.name] = this.value;
            }else {
                Json[this.name] =null;
            }
        });
    return Json;
}

/**
 * 模拟点击跳转
 * @param url
 */
var locationhref = function (url) {
    var el = document.createElement("a");
    document.body.appendChild(el);
    el.href = url; //url 是你得到的连接
    // el.target = '_new'; //指定在新窗口打开
    el.click();
    document.body.removeChild(el);
}

/**
 * webApi通讯
 * @param obj
 * @constructor
 */
var APIRequest = function (obj) {
    layui.use(['layer'],function (){
    var login = JSON.parse(localStorage.getItem("user"));
    //判断是否登录过,没登录的返回登录页
    if(login){//登录过的
        if(login===0){//登录过已经退出的
            window.location.href='../../pages/login.html';
            return false;
        }
    }else{
        window.location.href='../../pages/login.html';
        return false;
    }
    var layer = layui.layer;
    var _this = this;
    var xhr = new XMLHttpRequest();
    var opts = {
        url: "",
        method: "POST",
        header: {content_type: "application/json;charset=UTF-8",Authorization:getUser().token},
        data: null,
        cache: false,
        async: true,
        slide: true,
        success: function () {
        },
        error: function () {
        },
        beforeSubmit: function () {
        },
        afterSubmit: function () {
        }
    };
    var waitting = {};

    //比较,提交上来的请求包含哪些,然后封装到opts中
    for (var o in obj) {
        opts[o] = obj[o];
    }
    if (!opts.cache) {
        opts.url = opts.url + "?s=" + Math.random();
        //opts.url = opts.url;
    }
    /*if (opts.slide) {
        waitting = layer.msg('操作中,请稍候...');
    }*/
    opts.beforeSubmit();
    if ("withCredentials" in xhr) {
        xhr.open(opts.method, opts.url, opts.async);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(opts.method, opts.url);
    } else {
        opts.error({state: "01", msg: "浏览器不支持CORS"}, xhr);
        return;
    }
  //封装请求头
    for (var o in opts.header) {
        xhr.setRequestHeader(o, opts.header[o]);
    }
    xhr.onerror = function () {
        opts.afterSubmit();
        opts.error({code: "01", msg: "通讯异常"}, xhr);
    };
    xhr.onload = function () {
        opts.afterSubmit();
        var result = JSON.parse(xhr.responseText);
        if (result.code == 2001) {
           changePage("用户未登录,需登录");
        }else if (result.code == 2002) {
            changePage("账号已过期,需重新登录");
        }else if (result.code == 2004) {
            changePage("密码过期,需重新登录");
        }else if (result.code == 2008) {
            changePage("账号已存在,需重新登录");
        }else if (result.code ==2009) {
            changePage("账号下线,需重新登录");
        }else if (result.code == 3001) {
           layer.alert('无权访问');
        }else if (result.code == 500) {
           layer.alert('服务器异常');
        }else if (result.code == 999) {
           layer.alert('操作失败');
        }else if (result.code == 1001) {
           layer.alert('参数无效');
        }else if (result.code == 1002) {
           layer.alert('参数为空');
        }else if (result.code == 1003) {
           layer.alert('参数类型错误');
        }else if (result.code == 1004) {
           layer.alert('参数缺失');
        }else if (result.code == 2003) {
           layer.alert('用户名或密码错误');
        }else if (result.code == 2005) {
           layer.alert('账号不可用');
        } else if (result.code == 2006) {
            layer.alert('账号被锁定');
        }else if (result.code == 2007) {
            layer.alert('账号不存在');
        }else {
            opts.success(result, xhr);
        }

    };
    if (opts.method.toLocaleUpperCase() == "POST") {
        xhr.send(JSON.stringify(opts.data));
    }
    else {
        xhr.send();
    }

    });
}

//跳转到登录页
var changePage=function(msg) {
    layui.use(['layer'],function (){
        alert("登录过期,请重新登录");
        window.location.href = "../../pages/login.html";
    })
}
//登录时页面
var dologin=function (formData) {
    layui.use(['jquery','layer'],function () {
        var layer = layui.layer
            ,$=layui.jquery;
        $.post(global.api_url + "/login",formData.field, function(data){
            //需要转成json提出data数据再转成string数据类型来存,否则会出现问题
            var userdata=JSON.parse(data);
            var code=userdata.code;
            if (code==0){
                window.location.href='./admin/index.html';
                localStorage.setItem('user',JSON.stringify(userdata.data));
            }else {
                layer.msg(userdata.msg);
            }
        },"text");
    });
}
var getUser=function(){
    var user=localStorage.getItem("user");
    if (user!=undefined||user!=null){
        return JSON.parse(user);
    }else {//未登录,跳转到登录页
        locationhref("../login.html")
    }
    return null;
}

/**
 * 日其转换器
 * @param data 后台传过来的时间
 * @returns {string} 格式化后的时间
 */
function dateToStr(data){
    var d = new Date(data)
    var a= d.getFullYear() + '-' + (d.getMonth() + 1 < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1) + '-' + (d.getDate()<10 ? "0" +d.getDate():d.getDate())+ ' ' + (d.getHours()<10 ?"0"+d.getHours():d.getHours()) + ':' + (d.getMinutes()<10 ? "0" + d.getMinutes(): d.getMinutes()) + ':' + (d.getSeconds()<10 ? "0" + d.getSeconds() : d.getSeconds() );
    return a
}
function getRealPath(){
    var localObj = window.location;
    return localObj ;

}